package com.yuven.baselib.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.core.graphics.ColorUtils;

import com.yuven.baselib.R;


/**
 * 一些视图，显示，Toast，之类的工具方法
 * 1.显示Toast
 * 2.测量各种尺寸
 * 3.获取各种主题无关的资源 string, color
 */
public class ViewUtils {

    private static final int MSG_TOAST = 1;
    private static Handler mMainHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TOAST:
                    Toast.makeText(ToolsKit.getClient(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    /**
     * 显示一个toast 该方法已废弃
     * 统一使用com.hjq.toast.ToastUtils
     *
     * @param content
     * @param argus
     */
    @Deprecated
    public static void toast(String content, Object... argus) {
        if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
            Toast.makeText(ToolsKit.getClient(), String.format(content, argus), Toast.LENGTH_SHORT).show();
        } else {
            Message message = mMainHandler.obtainMessage(MSG_TOAST);
            message.obj = String.format(content, argus);
            message.sendToTarget();
        }
    }

    /**
     * 根据手机分辨率从DP转成PX
     *
     * @param dpValue
     * @return
     */
    public static int dip2px(float dpValue) {
        final float scale = ToolsKit.getClient().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(float spValue) {
        final float fontScale = ToolsKit.getClient().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率PX(像素)转成DP
     *
     * @param pxValue
     * @return
     */
    public static int px2dip(float pxValue) {
        float scale = ToolsKit.getClient().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2sp(float pxValue) {
        final float fontScale = ToolsKit.getClient().getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 获得屏幕的密度
     *
     * @return
     */
    public static int getScreenDensity() {
        return (int) ToolsKit.getClient().getResources().getDisplayMetrics().density;
    }


    /**
     * 获得屏幕的宽度
     *
     * @return
     */
    public static int getScreenWidth() {
        return ToolsKit.getClient().getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获得屏幕的高度
     *
     * @return
     */
    public static int getScreenHeight() {
        return ToolsKit.getClient().getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 获取导航栏的高度
     *
     * @return -1 如果无效
     */
    public static int getNavigationBarHeight() {
        Resources resources = ToolsKit.getClient().getResources();
        int height = -1;
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = resources.getDimensionPixelSize(resourceId);
        }
        return height;
    }

    /**
     * 隐藏导航栏
     *
     * @param window
     */
    public static void hideNavigation(Window window) {
        if (null == window)
            return;
        View decorView = window.getDecorView();
        decorView.setSystemUiVisibility(0);
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    /**
     * 获取状态栏的高度
     *
     * @return -1 如果无效
     */
    public static int getStatusHeight() {
        Resources resources = ToolsKit.getClient().getResources();
        int height = -1;
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = resources.getDimensionPixelSize(resourceId);
        }
        return height;
    }

    /**
     * 更改状态栏字体颜色
     *
     * @param activity
     * @param dark
     */
    public static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    /**
     * 设置状态栏颜色，并且根据状态栏颜色修改状态栏字体色值
     * 设置状态栏为沉浸式模式
     */
    public static void setStatusBarColorAndFullScreen(Activity activity, @ColorInt int color) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(color == 0 ? Color.TRANSPARENT : color);
            if (isLightColor(color)) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
        }
    }

    @SuppressLint("ResourceAsColor")
    public static void setLightStatusBar(Activity activity, boolean dark) {
        Window window = activity.getWindow();
        View decor = window.getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }

    }


    /**
     * 判断颜色是不是亮色
     */
    private static boolean isLightColor(@ColorInt int color) {
        return ColorUtils.calculateLuminance(color) >= 0.5;
    }

    /**
     * 页面全屏状态下设置电池状态栏高度
     *
     * @param view 一般为布局根View或顶部第一个View
     */
    public static void resizeTitleBar(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int topMargin = getStatusHeight();
            view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + topMargin, view.getPaddingRight(), view.getPaddingBottom());
        }
    }

    /**
     * 设置状态栏颜色
     */
    public static void setStatusBarColor(Activity activity, @ColorRes int color) {
        Window window = activity.getWindow();
        if (window != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.setStatusBarColor(ResourceUtil.getColor(color));
            int visibility = window.getDecorView().getSystemUiVisibility();
            visibility = visibility | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            window.getDecorView().setSystemUiVisibility(visibility);
        }
    }

    @TargetApi(21)
    public static void translucentStatusBar(Activity activity, boolean isDark) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (isDark) {//页面深色模式
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }


    @NonNull
    public static <T> T findView(@NonNull View root, @IdRes int id) {
        T view = (T) root.findViewById(id);
        return view;
    }

    /**
     * View to bitmap
     */
    public static Bitmap view2Bitmap(View view, int bgColor) {
        if (view == null) return null;
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(bgColor);  //避免黑底
        view.draw(canvas);
        return bitmap;
    }

    public static int getRealScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point realSize = new Point();
        display.getRealSize(realSize);
        return realSize.y;
    }

    public static void resizeText(TextView textView, int originalTextSize, int minTextSize) {
        final Paint paint = textView.getPaint();
        final int width = textView.getWidth();
        if (width == 0) return;
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, originalTextSize);
        float ratio = width / paint.measureText(textView.getText().toString());
        if (ratio <= 1.0f) {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                    Math.max(minTextSize, originalTextSize * ratio));
        }
    }
}
